package org.dandelion.papercheck.service.impl;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.dandelion.papercheck.common.exception.FileStorageException;
import org.dandelion.papercheck.config.FileStorageProperties;
import org.dandelion.papercheck.service.PaperService;
import org.dandelion.papercheck.util.OfficeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class PaperServiceImpl implements PaperService {
    private final Path fileStorageLocation;

    @Autowired
    public PaperServiceImpl(FileStorageProperties storageProperties) {
        this.fileStorageLocation = Paths.get(storageProperties.getUploadDir()).toAbsolutePath().normalize();
    }

    @Override
    public String preprocess(File file) {
        String fileName = file.getName();
        String text = null;

        try {
            if (fileName.endsWith(".doc")) {
                text = OfficeUtil.doc2Text(file);
            } else if (fileName.endsWith(".docx")) {
                text = OfficeUtil.docx2Text(file);
            }

            if (text != null) {
                text = text.replaceAll("\\s*", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return text;
    }

    @Override
    public List<String> splitWords(String text) {
        org.ansj.domain.Result result = ToAnalysis.parse(text);
        List<Term> termList = result.getTerms();

        var ret = new ArrayList<String>();

        for (var term : termList) {
            String s = term.getRealName();

            if (!s.trim().equals("")) {
                ret.add(term.getRealName());
            }
        }

        return ret;
    }

    @Override
    public List<String> splitWordsOfFile(String fileName) {
        Path path = fileStorageLocation.resolve(fileName);
        File file = path.toFile();

        if (!file.exists()) {
            throw new FileStorageException("Could not find file: " + fileName);
        }

        String text = preprocess(file);

        return splitWords(text);
    }
}
